package com.masterclient.app.utils;

import android.annotation.SuppressLint;
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;
import android.webkit.MimeTypeMap;

import com.eoner.baselibrary.utils.NetCheckUtil;
import com.eoner.baselib.utils.toast.ToastUtil;
import com.masterclient.app.base.ProgressLoginDialog;

import java.io.File;
import java.io.PrintWriter;
import java.io.StringWriter;

import static android.content.Context.DOWNLOAD_SERVICE;

public class DownLoadAsyncTasks extends AsyncTask<String, Integer, Boolean> {

    @SuppressLint("StaticFieldLeak")
    private Context mContext;
    private ProgressLoginDialog progressDialog;
    private long currentDownloadID;
    private boolean idDownloading = true;
    private boolean idDownloadSuccess = false;
    private String urlPath;
    private String resourcePath;
    private int type, urlSize;
    private String resourceName;
    private DownloadCallback downloadCallback;

    public interface DownloadCallback{
         // @param status 0完成 -1失败
        void onDownloadStatu(int status);
    }

    public DownLoadAsyncTasks(Context mContext, ProgressLoginDialog progressDialog, String urlPath,
                              String resourcePath, int type, DownloadCallback downloadCallback) {
        this.mContext = mContext;
        this.progressDialog = progressDialog;
        this.urlPath = urlPath;
        this.resourcePath = resourcePath;
        this.type = type;
        this.downloadCallback = downloadCallback;
    }

    @Override
    protected Boolean doInBackground(String... url) {
        download = 0;
        urlSize = url.length;
        for (String str: url) {
            urlPath = str;
            downloadByDownloadManager();
        }
        return true;
    }

    @Override
    protected void onPreExecute() {
        if (progressDialog != null) {
            progressDialog.show();
        }
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(Boolean aBoolean) {
        super.onPostExecute(aBoolean);
        Log.e("======onPostExecute", "==="+aBoolean);
        idDownloading = false;
        if (progressDialog != null) {
            new Handler().postDelayed(() -> progressDialog.dismiss(), 300);
        }
        if (aBoolean && idDownloadSuccess) {
            downloadCallback.onDownloadStatu(0);
            if (progressDialog != null) {
                ToastUtil.showToast(type == 1 ? "视频下载完成" : "图片已保存到相册");
            }
        } else {
            downloadCallback.onDownloadStatu(-1);
            if (progressDialog != null) {
                ToastUtil.showToast("下载失败，请重新下载");
            }

        }
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        if (isCancelled()) return;
        int value = values[0];
        if (value <= 100) {
            if (progressDialog != null) {
                progressDialog.setDesc(value + "%");
            }
        }
    }

    private int download = 0;
    // 4、下载器下载
    private void downloadByDownloadManager() {
        if (isCancelled()) return;
//        StringBuffer httpDownloadUrl = new StringBuffer("https://").append(HOST_PC_IP).append(downloadUrlStr);
        DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(urlPath));
        // 通过setAllowedNetworkTypes方法可以设置允许在何种网络下下载
        downloadRequest.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
        //设置下载通知栏显示
        downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
        // 文件后缀
        String fileFormat = "." + MimeTypeMap.getFileExtensionFromUrl(urlPath);
        // 获取文件名
        resourceName = System.currentTimeMillis() + fileFormat;
        // 本地保存地址
        String resourcePath = this.resourcePath;
        // 下载标题
        downloadRequest.setTitle("下载" + resourceName);
        File saveFile = new File(resourcePath, resourceName);
        downloadRequest.setDestinationUri(Uri.fromFile(saveFile));

        DownloadManager manager = (DownloadManager) mContext.getSystemService(DOWNLOAD_SERVICE);
        if (manager != null) {
            currentDownloadID = manager.enqueue(downloadRequest);
            Log.e("e", "DownloadManager start downloading ---------");
            // 获取下载进度
            getDownloadProgress(manager, resourceName);
        }
    }

    // 5下载进度并返回完成
    private void getDownloadProgress(final DownloadManager manager, final String resourceName) {
        if (isCancelled()) return;
        while (idDownloading) {
            DownloadManager.Query query = new DownloadManager.Query();
            query.setFilterById(currentDownloadID);
            Cursor cursor = manager.query(query);

            if (cursor.moveToFirst()) {
                long bytesDownloaded = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                long bytesTotal = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                final int downloadProgress = (int) (bytesDownloaded * 100 / bytesTotal);

                publishProgress(downloadProgress);
                Log.e("e", resourceName + ":下载进度: " + downloadProgress + "%");

                if (downloadProgress == 100) {
                    download++;
                    currentDownloadID = -1;
                    idDownloadSuccess = true;
                    if (type == 0){
                            Uri uri = Uri.fromFile(new File(resourcePath,resourceName));
                            mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
                    }
                    cursor.close();
                    break;
                } else {
                    try {
                        if (NetCheckUtil.checkNet(mContext)) {
                            Thread.sleep(300);
                        } else {
                            idDownloadSuccess = false;
                            cursor.close();
                            cancel(true);
                            remove(mContext);
                            downloadCallback.onDownloadStatu(download < 1?-1:0);
                            return;
                        }
                    } catch (InterruptedException e) {
                        cursor.close();
                        StringWriter stringWriter = new StringWriter();
                        e.printStackTrace(new PrintWriter(stringWriter, true));
                    }
                }
                /*int status = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS));
                if (status == DownloadManager.STATUS_PENDING) {
                    Log.e("status", "pengding");
                } else if (status ==DownloadManager.STATUS_PAUSED) {
                    Log.e("status", "paused");
                } else if (status == DownloadManager.STATUS_RUNNING) {
                    Log.e("status", "runing");
                } else if (status == DownloadManager.STATUS_SUCCESSFUL) {
                    Log.e("status", "successful");
                    break;
                } else if (status == DownloadManager.STATUS_FAILED) {
                    Log.e("status", "failed");
                    break;
                }*/
            }
            if (!cursor.isClosed()){
                cursor.close();
            }
        }
    }

    public void remove(Context context) {
        DownloadManager downloadManager = (DownloadManager) context.getSystemService(DOWNLOAD_SERVICE);
        if (currentDownloadID >= 0) {
            if (downloadManager != null) {
                downloadManager.remove(currentDownloadID);
            }
        }
        idDownloading = false;
    }
}
